import {
  Component, OnInit, ViewEncapsulation, Input,
  OnChanges, SimpleChanges, Output, EventEmitter, ViewChildren, QueryList, OnDestroy
} from '@angular/core';

import {Subject} from "rxjs";
import {GoodsSpecItemComponent} from "@goods/components/goods-spec-item/goods-spec-item.component";
import {ToolsService} from "@shared/service/tools/tools.service";
import {EventsService} from "@core/events/events.service";
import {GoodsRespVO} from "@interface/index";



@Component({
  selector: 'seed-goods-purchase',
  templateUrl: './goods-purchase.component.html',
  styleUrls: ['./goods-purchase.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class GoodsPurchaseComponent implements OnInit, OnChanges, OnDestroy {
  public params = [];
  public goodsStock = 0;
  private selectedParams = [];
  public selectedSore = {};
  private switcher = false;
  private _goodsPrice: number;
  private _isDisibled = true;
  private goodsUnitPrice: number;
  public ngUnsubscrible: Subject<void> = new Subject<void>();
  @Input() goods: GoodsRespVO;
  @Output() onSelected: EventEmitter<any> = new EventEmitter();
  @ViewChildren(GoodsSpecItemComponent) goodsSpecItem: QueryList<GoodsSpecItemComponent>;

  constructor(
    private tools: ToolsService,
    private events: EventsService
  ) {
    this.selectedSore['attrsName'] = [];
    this.selectedSore['attrsCode'] = [];
    this.selectedSore['price'];
    this.selectedSore['salePrice'];
    this.selectedSore['buyTimesLimit'] = 1;
    this.selectedSore['buyStatus'] = 0;
    this.selectedSore['isDisabled'] = true;
    this.selectedSore['quantity'] = 1;
  }


  /**
   * @description 设置 获取 商品总价
   * 商品价格 = (商品单价 * 数量)
   * @author @chenwh576
   * @date 20170923
   * @param val
   */
  set goodsPrice(val) {
    /*    this._goodsPrice = val * this.goodsUnitPrice;*/
    this._goodsPrice = val;
  }

  get goodsPrice() {
    return this._goodsPrice;
  }


  /**
   * @description 确认按钮
   * @author @chenwh576
   * @date 20170923
   * @param val
   */
  handleConfirm() {
    if (this.switcher) {
      this.onSelected.emit(this.selectedSore);
      this.events.publish('modal:close');
    }
    /*else {
      this.events.publish('modal:close');
    }*/
  }

  /**
   * @description 设置商品默认数据
   * @author @chenwh576
   * @date 20170923
   * @param val
   */
  handleInitDate() {
    this.selectedSore['goodsStock'] = this.goods.totalStock;
    this.selectedSore['buyTimesLimit'] = 1;
  }

  /**
   * @description 设置确认按钮状态
   * @author @chenwh576
   * @date 20170923
   * @param val
   */
  /* isDisabled():boolean{
   return this.selectedSore['isDisabled'] && this.selectedSore['buyStatus'] == 0;
   }*/

  set isDisabled(val) {
    this._isDisibled = val;
  }

  get isDisabled(): boolean {
    return this._isDisibled;
  }

  handleDisabled() {
    if (this.selectedSore['isDisabled']
      || this.selectedSore['buyStatus'] === 0
      || this.selectedSore['goodsStock'] === 0
    ) {
      this.isDisabled = true;
    } else {
      this.isDisabled = false;
    }
  }

  /**
   * @description 每个商品item点击后选择的list
   * @author @chenwh576
   * @date 20170923
   * @param val
   */
  handleSelectedItem(event) {
    this.selectedSore['selectedIndex'] = event.index;
    this.selectedParams[event.row] = event;
    this.selectedSore['attrsCode'][event.row] = `"${this.selectedParams[event.row].attrCode}"`;
    this.selectedSore['attrsName'][event.row] = `"${this.selectedParams[event.row].attrValueName}"`;
    this.disposeSkuList(event.row);
  }


  removeByValue(arr, val) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === val) {
        arr.splice(i, 1);
        return arr;
      }
    }
  }

  /**
   * @description 获取数组长度真实长度
   * @author @chenwh576
   * @date 20170923
   * @param obj
   * @returns {any}
   */
  handleArrayLength(obj) {
    const objType = typeof obj;
    if (objType === "string") {
      return obj.length;
    } else if (objType === "object") {
      let objLen = 0;
      for (const i in obj) {
        objLen++;
      }
      return objLen;
    }
    return false;
  }

  /**
   * @description 获取counter组件里面选择的数量
   * @author @chenwh576
   * @date 20170923
   * @param obj
   * @returns {any}
   */
  handleSelectedQuantity(event) {
    if (event) {
      this.selectedSore['quantity'] = event;
      const buyTimesLimit = this.selectedSore['buyTimesLimit'];
      if (event === buyTimesLimit) {
        this.tools.showToast(`该商品最多只能购买${buyTimesLimit}件.`);
      }
    }
  }

  /**
   * @description 处理skulist 如果商品item选择状态的长度与商品skulist长度一样执行this.composeSkuList
   * @author @chenwh576
   * @date 20170923
   * @param obj
   * @returns {any}
   */
  disposeSkuList(idx) {
    const goodsSpecItemLength = this.goodsSpecItem.toArray().length;
    if (this.handleArrayLength(this.selectedSore['attrsCode']) === goodsSpecItemLength) {
      this.goodsSpecItem.toArray().forEach((item, i) => {
        if ((typeof  item.current !== 'undefined') && (idx === i)) {
          this.composeSkuList();
        }
      });
    }

  }

  /**
   * @description 组装用户选择的商品sku list
   * @author @chenwh576
   * @date 20170923
   * @param obj
   * @returns {any}
   */
  composeSkuList() {
    let skuList = this.goods.skuList;
    try {
      skuList.forEach((v, i) => {
        const sortByattrsCode = this.selectedSore['attrsCode'].sort().toString().replace(/\"/g, "");
        const sort = v.attrCodeList.sort().toString().replace(/\"/g, "");
        if (sort === sortByattrsCode) {
          this.goodsPrice = v.salePrice;
          this.selectedSore['goodsStock'] = v.stock;
          this.selectedSore['price'] = v.price;
          this.selectedSore['salePrice'] = this.goodsPrice;
          this.selectedSore['buyTimesLimit'] = v.buyTimesLimit === 0 ? v.stock : v.buyTimesLimit;
          this.selectedSore['isDisabled'] = false;
          this.selectedSore['skuCode'] = v.skuCode;
          this.selectedSore['buyStatus'] = v.buyStatus;
          this.switcher = true;
          this.handleDisabled();
          throw 'BreakException';
        } else {
          this.resetStore();
          this.handleDisabled();
        }
      });
    } catch (e) {

    }
  }

  resetStore() {
    this.selectedSore['goodsStock'] = 0;
    this.selectedSore['buyTimesLimit'] = 1;
    this.selectedSore['buyStatus'] = 0;
    this.selectedSore['isDisabled'] = true;
    this.selectedSore['quantity'] = 1;
  }


  // 关闭模态框
  closeModal() {
    this.events.publish('modal:close');
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['goods'].currentValue && !this.tools.isEmptyObject(changes['goods'].currentValue)) {
      this.handleInitDate();
    }
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    this.ngUnsubscrible.next();
    this.ngUnsubscrible.complete();
  }

}
